 package com.example.red_tea_house.moudle.LoginAndRegister.view;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ToggleButton;

import androidx.appcompat.app.AppCompatActivity;

import com.example.red_tea_house.R;
import com.example.red_tea_house.annotation.HandlerType;

import com.example.red_tea_house.annotation.UserType;
import com.example.red_tea_house.entity.LoginBean;
import com.example.red_tea_house.entity.UserBean;
import com.example.red_tea_house.moudle.LoginAndRegister.controller.LoginController;

import com.example.red_tea_house.util.ViewUtil;

import okhttp3.Call;

 public class LoginActivity extends AppCompatActivity {
     private EditText mEdit_username;
     private EditText mEdit_password;
     private ToggleButton mToggleButton;
     private Button mButton_login;
     private Button mButton_register;
     private Button mButton_forget_password;
     private Button mButton_identify_login;
     private ImageButton mButton_returnMainPage;

     private LoginBean loginBean=new LoginBean();

     private final int intentCodeForRegister=1;
     private final int intentCodeForVertifyLogin=2;

     private LoginController loginController=new LoginController(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.log_in_page);

        bindItems();

        autoLogin();

        ClickLoginButton();

        turnIntoRegister();
        turnIntoForgetPassword();
        turnIntoIndentifyLogin();

        returnMainPageWithOutLogin();

        /*
        * 实现密码可见与不可见
        * */
        mToggleButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
             mEdit_password=findViewById(R.id.Edit_password);
            if(isChecked){
                mEdit_password.setTransformationMethod(null);
            }else{
                mEdit_password.setTransformationMethod(new PasswordTransformationMethod());
            }
                });
            if(getSupportActionBar()!=null){
                getSupportActionBar().hide();}

        /*
        * 实现11位账号自动跳转
        * */
        mEdit_username.addTextChangedListener(new TextWatcher(){
            private CharSequence mStr; // 声明一个文本串
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mStr = s;
            }

            @Override
            public void afterTextChanged(Editable s) {
                if(mStr == null || mStr.length() ==1)
                    return;
                // 输入文本达到11位时关闭输入法
                if(mStr.length() == 11 ){
                    ViewUtil.hideAllInputMethod(LoginActivity.this);
                    mEdit_password.requestFocus();
                }
            }
        });

    }

     private void bindItems(){
         mEdit_username=findViewById(R.id.Edit_username);
         mEdit_password=findViewById(R.id.Edit_password);
         mButton_login=findViewById(R.id.btn_login);
         mButton_register=findViewById(R.id.btn_register);
         mButton_forget_password=findViewById(R.id.forget_password);
         mButton_identify_login=findViewById(R.id.identifying_code_log);
         mButton_returnMainPage=findViewById(R.id.login_close);
         mToggleButton=findViewById(R.id.password_eye);
     }
     private void ClickLoginButton() {
         mButton_login.setOnClickListener((v)-> {
             loginBean.setPhone(mEdit_username.getText().toString());
             loginBean.setPassword(mEdit_password.getText().toString());
             loginController.loginJudge(loginBean);
         });
     }
     private void autoLogin(){
         if(getSharedPreferences("loginState",MODE_PRIVATE).getBoolean("loginstate",false)){
             returnLoginStateMessage(UserType.DefaultNickName,UserType.DefaultAutoGraph);
         }
     }
     private void returnMainPageWithOutLogin(){
        mButton_returnMainPage.setOnClickListener((v)->finish());
     }


    private void turnIntoRegister(){
        mButton_register.setOnClickListener((v)-> {
            Intent intent=new Intent(LoginActivity.this, RegisterActivity.class);
            startActivityForResult(intent,intentCodeForRegister);
        });
    }
    private void turnIntoForgetPassword(){
        mButton_forget_password.setOnClickListener((v)->{
            Intent intent=new Intent(LoginActivity.this, ForgetPasswordAcitivity.class);
            startActivity(intent);
        });
    }
    private void turnIntoIndentifyLogin(){
        mButton_identify_login.setOnClickListener((v)->{
            Intent intent=new Intent(LoginActivity.this, VertifyLoginActivity.class);
            startActivityForResult(intent,intentCodeForVertifyLogin);
        });
    }
    /*
    * 如果是注册，接受Intent返回的账号密码信息，并将其自动填入Edittext；如果是验证码登录且成功，进入主页面
    * */
    @Override
    protected void onActivityResult(int requestCode,int resultCode,Intent data){
        super.onActivityResult(requestCode,resultCode,data);
        switch (requestCode){
            case intentCodeForRegister:
                if(resultCode==RESULT_OK){
                    String phone=data.getStringExtra("phone_return");
                    String password=data.getStringExtra("password_return");
                    mEdit_username.setText(phone);
                    mEdit_password.setText(password);
                }
            case intentCodeForVertifyLogin:
                if(resultCode==RESULT_OK){
                    int loginState=data.getIntExtra("vertifyLoginState",0);
                    if(loginState== HandlerType.VERTIFY_LOGIN_SUCCESS){
                        returnLoginStateMessage(UserType.DefaultNickName,UserType.DefaultAutoGraph);
                    }
                }
        }
    }
    public void returnLoginStateMessage(String nickname,String autograph){
        saveUserData(nickname,autograph);

        Intent intent=new Intent();
        intent.putExtra("LoginState",true);
        setResult(RESULT_OK,intent);
        finish();
    }
     private void saveUserData(String nickname,String autograph){
         UserBean userBean=new UserBean();
         userBean.setPhone(loginBean.getPhone());
         userBean.setPassword(loginBean.getPassword());
         userBean.setNickname(nickname);
         userBean.setAutograph(autograph);
         userBean.save();
     }

}